package com.stone.name.space.parser;

import com.stone.name.space.bean.PeopleDto;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

/**
 * <p>Created with IntelliJ IDEA. </p>
 * <p>User: Stony </p>
 * <p>Date: 2016/6/24 </p>
 * <p>Time: 11:29 </p>
 * <p>Version: 1.0 </p>
 */
public class PeopleBeanDefinitionParser extends AbstractBeanDefinitionParser {


    /**
     * @param beanClass
     * @param required
     */
    public PeopleBeanDefinitionParser(Class<?> beanClass, boolean required) {
        super(beanClass, required);
    }

    @Override
    public BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
        RootBeanDefinition beanDefinition = getBaseRootBeanDefinition(element, parserContext, beanClass, required);

        beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, getRuntimeBeanReference(element,parserContext));
        return beanDefinition;
    }

    private RuntimeBeanReference getRuntimeBeanReference(Element element,ParserContext parserContext){
        String reg_id = PeopleDto.class.getSimpleName();
        RootBeanDefinition beanDefinition = new RootBeanDefinition();
        beanDefinition.setBeanClass(PeopleDto.class);
        beanDefinition.setLazyInit(false);
        String name = element.getAttribute("name");
        String age = element.getAttribute("age");
        beanDefinition.getPropertyValues().add("name", name);
        beanDefinition.getPropertyValues().add("age", Integer.valueOf(age));
        beanDefinition.getPropertyValues().addPropertyValue("id", element.getAttribute("id"));
        parserContext.getRegistry().registerBeanDefinition(reg_id, beanDefinition);
        return new RuntimeBeanReference(reg_id);
    }
}
